import type {FC, PropsWithChildren} from 'react';
import {CSSProperties, memo, useEffect, useMemo, useRef, useState,} from 'react';
//@ts-ignore
import {Chat, ContactItem, ContactList} from 'react-jwchat';
import {userStore} from '@/store/userStore';
import {useWebSocket} from 'ahooks';
import {useRecoilValue} from 'recoil';
import {contact, contactList, my} from '@/pages/Message/displayData';
import {Contact} from "@/pages/Message/typing";
import {currentUserDataStore, currentUserStore, MessageType, userDataStore, userListStore} from "@/store/chatStore";

enum ReadyState {
  Connecting = 0,
  Open = 1,
  Closing = 2,
  Closed = 3,
}

const listStyle: CSSProperties = {
  marginRight: 10,
  height: 500,
  borderRadius: 5,
  width: 240,
  border: '1px solid rgb(226, 226, 226)',
};

const styleContain: CSSProperties = {
  height: 'calc(100vh - 55px)',
};

const styleChat: CSSProperties = {
  width: 600,
  height: 500,
  borderRadius: 5,
  border: '1px solid rgb(226, 226, 226)',
};

const MessagePage: FC<PropsWithChildren<{}>> = () => {
  const user = useRecoilValue(userStore);
  const userList = useRecoilValue(userListStore);
  const currentUser = useRecoilValue(currentUserStore);
  const currentUserData = useRecoilValue(currentUserDataStore);

  const {readyState, sendMessage, latestMessage, disconnect, connect} =
      useWebSocket(
          'ws://localhost:8081',
      );

  useEffect(() => {
    if (readyState === ReadyState.Open && user.id > 0) {
      sendMessage && sendMessage(JSON.stringify({id: user.id, type: MessageType.USER_ID}))
    }
  }, [readyState, user, sendMessage])

  useEffect(() => {
    if (latestMessage?.isTrusted) {
      const data = JSON.parse(latestMessage.data)
      switch (data?.type) {
        case MessageType.CHAT:
          console.log(data)
          break;
        case MessageType.USER_DATA:
          console.log(data)
          break;
        case MessageType.USER_LIST:
          console.log(data)
          break;
      }
    }
  }, [latestMessage])

  const [chatListData, setChatListData] = useState<any[]>([]);

  return (
      <div className={'flex-justify-items-center w-screen'} style={styleContain}>
        <div className={'h-[500px] flex'}>
          <ContactList
              data={contactList}
              style={listStyle}
              onSelect={(contact: Contact) => sendMessage && sendMessage(JSON.stringify({
                id: 3,
                type: MessageType.USER_DATA
              }))}
          />
          <Chat
              contact={contact}
              me={my}
              chatList={chatListData}
              onSend={(msg: any) => setChatListData([...chatListData, msg])}
              onEarlier={() => console.log('EarlierEarlier')}
              style={styleChat}
          />
        </div>
      </div>
  );
};

export default memo(MessagePage);
